package com.esgpro.esg_api.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esgpro.esg_api.pojo.User;
import com.esgpro.esg_api.service.Impl.UserServiceImpl;
import com.esgpro.esg_api.util.JSONResult;
import com.google.code.kaptcha.Constants;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Api(tags = "token查询列表")
@RequestMapping("/token")
public class TokenController {
    @Autowired
    UserServiceImpl service;
    @Autowired
    JSONResult result;

    @PostMapping("/login")
    public JSON login(HttpServletRequest request, @RequestParam("code")String code,@RequestParam("account") int account,@RequestParam("password") String password) {
        User user = service.Login(account, password);
        StpUtil.login(1);
        String sessionCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println(" session中获取的验证码:  " + sessionCode);
        if (code.equalsIgnoreCase(sessionCode)){
            JSONObject obj = this.result.putMapInResult("user", user);
            obj.put("message","验证码相同,验证通过");
            if (StpUtil.isLogin()) {
                obj.put("token", StpUtil.getTokenInfo());
                return obj;
            }
        }

        return result.getResult(false);
    }

    @GetMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }


    @GetMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
